using System;
using System.IO;
using System.Reflection;

namespace Graphe.RobinsonPierpont
{
    public class Parser
    {
        private static BookCollection _books;

        public static BookCollection Parse()
        {
            if (_books != null)
                return _books;

            _books = new BookCollection();

            Assembly ass = Assembly.GetExecutingAssembly();
            using (Stream stream = ass.GetManifestResourceStream("Graphe.Resources.RP2005Unicode.txt"))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    reader.ReadLine();
                    string line = null;
                    Book currentBook = null;
                    Chapter currentChapter = null;
                    bool newBook = false;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line.Trim() == String.Empty)
                            continue;

                        if (line[2] != ':')
                        {
                            string currentBookName = line.Trim();
                            currentBook = new Book();
                            currentBook.Name = currentBookName;

                            _books.Add(currentBook);

                            newBook = true;
                        }
                        else
                        {
                            string text = line.Substring(6, line.Length - 6);
                            string[] referenceArray = line.Substring(0, 5).Trim().Split(new char[] { ':' });

                            int chapterNumber = Convert.ToInt32(referenceArray[0]);
                            int verseNumber = Convert.ToInt32(referenceArray[1]);

                            if (currentChapter == null || currentChapter.Number != chapterNumber || newBook)
                            {
                                currentChapter = new Chapter();
                                currentChapter.Number = chapterNumber;
                                currentBook.Chapters.Add(currentChapter);

                                if (newBook)
                                    newBook = false;
                            }

                            Verse verse = new Verse();
                            verse.Number = verseNumber;
                            verse.Text = text;

                            currentChapter.Verses.Add(verse);
                        }
                    }
                }
            }

            return _books;
        }
    }
}
